package com.mazewei.dev.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

public class ExcelReader {
    public static void main(String[] args) {
        String filePath = "uploads/2024-2025（1）任课数据安排表.xls";
        
        try (FileInputStream fis = new FileInputStream(filePath)) {
            Workbook workbook;
            if (filePath.toLowerCase().endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else {
                workbook = new HSSFWorkbook(fis);
            }
            
            System.out.println("工作表数量: " + workbook.getNumberOfSheets());
            
            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                Sheet sheet = workbook.getSheetAt(sheetIndex);
                System.out.println("\n工作表 " + sheetIndex + ": " + sheet.getSheetName());
                System.out.println("总行数: " + (sheet.getLastRowNum() + 1));
                
                // 读取前5行数据
                for (int rowIndex = 0; rowIndex <= Math.min(4, sheet.getLastRowNum()); rowIndex++) {
                    Row row = sheet.getRow(rowIndex);
                    if (row != null) {
                        System.out.print("第" + (rowIndex + 1) + "行: ");
                        for (int colIndex = 0; colIndex < Math.min(10, row.getLastCellNum()); colIndex++) {
                            Cell cell = row.getCell(colIndex);
                            String cellValue = getCellValueAsString(cell);
                            System.out.print("[" + cellValue + "] ");
                        }
                        System.out.println();
                    }
                }
            }
            
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }
        
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf((long) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}